﻿using Microsoft.Extensions.Hosting;
using System.Diagnostics;

namespace ConsoleTest.Services
{
    public class DiagnosticListenerService : IHostedService
    {
        private readonly MyListener myListener = new();
        private readonly DiagnosticListener listener = new("MyListener");
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            DiagnosticListener.AllListeners.Subscribe(myListener);
            listener.Write("MyEvent", new { Message = "Hello World" });
            await Task.CompletedTask;
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await Task.CompletedTask;
        }
    }
    public class MyListener : IObserver<DiagnosticListener>
    {
        private IDisposable? subscription;
        public void OnCompleted() 
            => subscription?.Dispose();

        public void OnError(Exception error)
        {
            Console.WriteLine($"Error: {error.Message}");
        }

        public void OnNext(DiagnosticListener value)
        {
            if (value.Name == "MyListener")
            {
                subscription = value.Subscribe(new MyListenerObserver());
            }
        }
    }
    public class MyListenerObserver : IObserver<KeyValuePair<string, object?>>
    {
        public void OnCompleted()
        {
        }

        public void OnError(Exception error)
        {
            Console.WriteLine($"Error: {error.Message}");
        }

        public void OnNext(KeyValuePair<string, object?> value)
        {
            Console.WriteLine($"EventName: {value.Key} - Payload: {value.Value}");
        }
    }
}
